package com.ssly.media.manage.controller.api;

import com.ssly.media.manage.configuration.MediaProperties;
import com.ssly.media.manage.domain.DownTask;
import com.ssly.media.manage.domain.SourceMedia;
import com.ssly.media.manage.repository.DownTaskRepository;
import com.ssly.media.manage.repository.SourceMediaRepository;
import com.ssly.media.manage.service.SourceMediaService;
import com.ssly.media.manage.util.DownLoad;
import com.ssly.media.manage.util.JsonResult;
import com.ssly.media.manage.util.R;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.sql.Timestamp;
import java.util.Optional;

import static java.lang.Thread.sleep;


@RestController
@RequestMapping("api/source-media")
public class SourceMediaController {

    @Autowired
    private DownTaskRepository downTaskRepository;
    @Autowired
    private SourceMediaRepository sourceMediaRepository;
    @Autowired
    private MediaProperties mediaProperties;

    @GetMapping("/{id}")
    public JsonResult show(@PathVariable Integer id) {
        return R.success();
    }

    @GetMapping
    public DataTablesOutput<SourceMedia> index(DataTablesInput input) {
        return sourceMediaRepository.findAll(input);
    }

    @PutMapping
    public JsonResult update() {
        return R.success();
    }

    @PostMapping
    public JsonResult create(DownTask downTask) {
        return R.success();
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable Integer id) {

        Optional<SourceMedia> optional = sourceMediaRepository.findById(id);
        if (optional.isPresent()){
            SourceMedia sourceMedia = optional.get();
            String savePath = sourceMedia.getSavePath();
            File file = new File(savePath);
            sourceMediaRepository.deleteById(id);
            if (file.delete()){
                return R.success("删除成功");
            }else {
                return R.success("数据库删除成功,文件删除失败");
            }
        }else {
            return R.error("删除失败");
        }
    }

}
